<template>
    <!-- 表单查询 -->
    <el-card style="margin-bottom: 10px;">
        <el-form :inline="true" class="demo-form-inline" style="margin-top: 10px;">
            <el-form-item label="用户账户">
                <el-input v-model="pageinfo.UserAccount" placeholder="请输入用户账户" clearable />
            </el-form-item>
            <el-form-item label="用户姓名">
                <el-input v-model="pageinfo.UserName" placeholder="请输入用户姓名" clearable />
            </el-form-item>
            <el-form-item label="岗位名称">
                <el-select v-model="pageinfo.PositionId" placeholder="请选择" clearable>
                    <el-option :label="item.positionName" :value="item.positionId" v-for="item in PositionTableData"
                        :key="item.positionId" />
                </el-select>
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="pageinfo.Status" placeholder="请选择" clearable>
                    <el-option label="启用" value="1" />
                    <el-option label="停用" value="0" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="GetUser">查询</el-button>
                <el-button type="info" @click="resetUser">重置</el-button>
            </el-form-item>
        </el-form>
    </el-card>
    <!-- 操作按钮 -->
    <el-card style="margin-bottom: 10px;">
        <el-button type="primary" @click="handleAdd">
            <el-icon>
                <Plus />
            </el-icon>新增
        </el-button>
        <el-button @click="handleBatchDelete" type="danger">删除</el-button>
        <el-button @click="handleBatchEnable" type="success">启用</el-button>
        <el-button @click="handleBatchDisable" type="warning">停用</el-button>
    </el-card>

    <!-- 用户列表数据 -->
    <el-card style="margin-bottom: 10px;">
        <el-table ref="multipleTableRef" :data="tableData" row-key="userId" style="width: 100%; margin-top: 10px;"
            @selection-change="handleSelectionChange" height="440px">
            <el-table-column type="selection" width="55" fixed="left" />
            <el-table-column type="index" label="序号" width="55" fixed="left" />
            <el-table-column property="userAccount" label="用户账号" width="140" fixed="left">
                <template #default="scope">
                    <a>{{ scope.row.userAccount }}</a>
                </template>
            </el-table-column>
            <el-table-column property="userName" label="用户姓名" width="120" />
            <el-table-column property="userSex" label="性别" width="60">
                <template #default="scope">
                    <span>{{ getSexName(scope.row.userSex) || '-' }}</span>
                </template>
            </el-table-column>
            <el-table-column property="userPhone" label="手机号" width="120" />
            <el-table-column property="positionName" label="岗位名称" width="120" />
            <el-table-column property="organizationName" label="所在部门" width="120" />
            <el-table-column property="roleName" label="角色" width="150">
                <template #default="scope">
                    <el-tag
                        v-for="role in (scope.row.roleNames || []).length > 0 ? scope.row.roleNames : (scope.row.roleName ? [scope.row.roleName] : [])"
                        :key="role" size="small" style="margin-right: 5px; margin-bottom: 2px;">
                        {{ role }}
                    </el-tag>
                    <span
                        v-if="(!scope.row.roleNames || scope.row.roleNames.length === 0) && !scope.row.roleName">-</span>
                </template>
            </el-table-column>
            <el-table-column property="userSort" label="排序" width="70" />
            <el-table-column property="userState" label="状态" width="80">
                <template #default="scope">
                    <span v-if="scope.row.userState === 1">启用</span>
                    <span v-else-if="scope.row.userState === 0">停用</span>
                </template>
            </el-table-column>
            <el-table-column property="userNote" label="备注" width="150" show-overflow-tooltip />
            <el-table-column label="操作" fixed="right" width="170">
                <template #default="scope">
                    <el-button link size="small" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button link size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>
    <!-- 分页 -->
    <el-card>
        <el-pagination v-model:current-page="pageinfo.Pageindex" v-model:page-size="pageinfo.PageSize"
            :page-sizes="[10, 20, 30, 40]" :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="pageinfo.listCount" />
    </el-card>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" @close="handleDialogClose">
        <el-form ref="userFormRef" :model="userForm" :rules="userFormRules" label-width="100px">
            <el-row :gutter="20">
                <!-- 左列 -->
                <el-col :span="12">
                    <el-form-item label="用户账号 *" prop="userAccount">
                        <el-input v-model="userForm.userAccount" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="性别" prop="userSex">
                        <el-select v-model="userForm.userSex" placeholder="请选择" style="width: 100%" clearable>
                            <el-option :label="item.dictionaryName" :value="item.dictionaryId"
                                v-for="item in SexOptions" :key="item.dictionaryId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="岗位名称" prop="positionId">
                        <el-select v-model="userForm.positionId" placeholder="请选择" style="width: 100%">
                            <el-option :label="item.positionName" :value="item.positionId"
                                v-for="item in PositionTableData" :key="item.positionId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="userState">
                        <el-radio-group v-model="userForm.userState">
                            <el-radio :label="1">启用</el-radio>
                            <el-radio :label="0">停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="角色" prop="roleIds">
                        <el-checkbox-group v-model="userForm.roleIds" style="width: 100%">
                            <el-checkbox :label="item.roleId" v-for="item in RoleTableData" :key="item.roleId">
                                {{ item.roleName }}
                            </el-checkbox>
                        </el-checkbox-group>
                    </el-form-item>
                    <el-form-item label="备注" prop="userNote">
                        <el-input v-model="userForm.userNote" type="textarea" :rows="4" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <!-- 右列 -->
                <el-col :span="12">
                    <el-form-item label="用户姓名 *" prop="userName">
                        <el-input v-model="userForm.userName" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="userPhone">
                        <el-input v-model="userForm.userPhone" placeholder="请输入" />
                    </el-form-item>
                    <el-form-item label="所在部门" prop="organizationId">
                        <el-tree-select v-model="userForm.organizationId" :data="OrganizationTreeData"
                            :props="{ value: 'id', label: 'label', children: 'children' }" placeholder="请选择部门"
                            style="width: 100%" check-strictly :render-after-expand="false" node-key="organizationId"
                            clearable />
                    </el-form-item>
                    <el-form-item label="排序" prop="userSort">
                        <el-input v-model.number="userForm.userSort" placeholder="请输入" type="number" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="success" @click="handleSave">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch, nextTick } from 'vue'
import myaxios from "@/http/MyAxios";
import { ElMessage, ElMessageBox, type TableInstance, type FormInstance, type FormRules } from 'element-plus'
import { useRouter } from 'vue-router';
import { Plus } from '@element-plus/icons-vue'

const router = useRouter();

// 分页查询条件
const pageinfo = reactive({
    pageCount: 0,
    listCount: 0,
    Pageindex: 1,
    PageSize: 10,
    UserAccount: "",
    UserName: "",
    PositionId: null,
    Status: null,
})

// 多选
const multipleTableRef = ref<TableInstance>()
const multipleSelection = ref<any[]>([])

const handleSelectionChange = (val: any[]) => {
    multipleSelection.value = val
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增')
const userFormRef = ref<FormInstance>()
const isEdit = ref(false)

// 用户表单数据
const userForm = reactive({
    userId: null,
    userAccount: '',
    userName: '',
    userSex: null as number | null,
    userPhone: '',
    positionId: null,
    organizationId: null,
    roleIds: [] as number[],
    userSort: 0,
    userState: 1,
    userNote: '',
})

// 表单验证规则
const userFormRules: FormRules = {
    userAccount: [
        { required: true, message: '请输入用户账号', trigger: 'blur' }
    ],
    userName: [
        { required: true, message: '请输入用户姓名', trigger: 'blur' }
    ],
    positionId: [
        { required: true, message: '请选择岗位', trigger: 'change' }
    ],
    organizationId: [
        { required: true, message: '请选择所在部门', trigger: 'change' }
    ],
    roleIds: [
        {
            required: true,
            type: 'array',
            min: 1,
            message: '请至少选择一个角色',
            trigger: 'change'
        }
    ],
}

// 岗位信息接收
const PositionTableData: any = ref([])

// 岗位信息请求
const GetPosition = () => {
    myaxios({
        url: "/api/Position/GetPositionOptions",
        method: "get",
    })
        .then(res => {
            PositionTableData.value = res.data.data || [];
        })
        .catch(err => {
            console.log(err);
        })
}
// 部门树形数据接收
const OrganizationTreeData: any = ref([])
// 部门树形数据请求
const GetOrganizationTree = () => {
    myaxios({
        url: "/api/Organization/GetOrganizationTree",
        method: "get"
    })
        .then(res => {
            OrganizationTreeData.value = res.data

        })
        .catch(err => {
            console.log(err);
            ElMessage.error('获取部门树形数据失败');
        })
}

// 角色信息接收
const RoleTableData: any = ref([])
// 角色信息请求
const GetRole = () => {
    myaxios({
        url: "/api/Role/GetRoleSelectList",
        method: "get",
    })
        .then(res => {
            RoleTableData.value = res.data.data || [];
        })
        .catch(err => {
            console.log(err);
        })
}

// 性别字典选项接收
const SexOptions = ref<any[]>([])
// 获取性别字典选项
const GetSexOptions = async () => {
    try {
        // 先获取所有字典列表，不传查询条件，获取所有父级字典
        const searchRes = await myaxios.get('/api/Dictionary/GetDictionaryList', {
            params: {
                Pageindex: 1,
                PageSize: 1000  // 获取更多数据以确保能找到
            }
        })

        if (searchRes.data?.code === 200) {
            const allData = searchRes.data.data?.data || []
            // 查找父级字典（性别）- 优先使用字典名称匹配
            let sexDictionary = allData.find((item: any) => {
                const isParent = !item.parentId || item.parentId === 0 || item.parentId === null
                const nameMatch = item.dictionaryName === '性别' || item.dictionaryName?.includes('性别')
                const codeMatch = item.dictionaryCode === '性别' || item.dictionaryCode?.toUpperCase() === 'SEX'
                return isParent && (nameMatch || codeMatch)
            })

            // 如果没找到，尝试用字典名称查询
            if (!sexDictionary) {
                const nameSearchRes = await myaxios.get('/api/Dictionary/GetDictionaryList', {
                    params: {
                        DictionaryName: '性别',
                        Pageindex: 1,
                        PageSize: 100
                    }
                })

                if (nameSearchRes.data?.code === 200) {
                    const nameData = nameSearchRes.data.data?.data || []
                    sexDictionary = nameData.find((item: any) =>
                        (!item.parentId || item.parentId === 0 || item.parentId === null) &&
                        (item.dictionaryName === '性别' || item.dictionaryName?.includes('性别'))
                    )
                }
            }

            if (sexDictionary && sexDictionary.dictionaryId) {
                // 获取性别字典的子级配置项
                const childrenRes = await myaxios.get('/api/Dictionary/GetDictionaryChildren', {
                    params: {
                        ParentId: sexDictionary.dictionaryId,
                        Pageindex: 1,
                        PageSize: 100
                    }
                })

                if (childrenRes.data?.code === 200) {
                    const childrenData = childrenRes.data.data?.data || []
                    if (childrenData.length > 0) {
                        SexOptions.value = childrenData.map((item: any) => ({
                            dictionaryId: Number(item.dictionaryId), // 确保是数字类型
                            dictionaryCode: item.dictionaryCode,
                            dictionaryName: item.dictionaryName,
                            description: item.dictionaryDesc || item.description || ''
                        }))
                        return  // 成功获取，直接返回
                    }
                }
            }

            // 如果找不到性别字典或子项，使用默认值
            console.warn('未找到性别字典或子项，使用默认值。请检查字典管理中是否已配置"性别"字典及其子项。')
            SexOptions.value = [
                { dictionaryId: 1, dictionaryCode: '1', dictionaryName: '男' },
                { dictionaryId: 2, dictionaryCode: '0', dictionaryName: '女' }
            ]
        } else {
            console.warn('获取字典列表失败，使用默认值')
            SexOptions.value = [
                { dictionaryId: 1, dictionaryCode: '1', dictionaryName: '男' },
                { dictionaryId: 2, dictionaryCode: '0', dictionaryName: '女' }
            ]
        }
    } catch (err) {
        console.error('获取性别字典失败:', err)
        // 如果获取失败，使用默认值
        SexOptions.value = [
            { dictionaryId: 1, dictionaryCode: '1', dictionaryName: '男' },
            { dictionaryId: 2, dictionaryCode: '0', dictionaryName: '女' }
        ]
    }
}

// 根据性别代码获取性别名称
const getSexName = (sexCode: any) => {
    if (sexCode === null || sexCode === undefined) return ''
    // 优先通过 dictionaryId 查找（数字）
    const sexNum = Number(sexCode)
    if (!isNaN(sexNum)) {
        const sexItemById = SexOptions.value.find(item => item.dictionaryId === sexNum)
        if (sexItemById) {
            return sexItemById.dictionaryName
        }
    }
    // 兼容旧数据：通过 dictionaryCode 查找（字符串）
    const sexStr = String(sexCode)
    const sexItemByCode = SexOptions.value.find(item => item.dictionaryCode === sexStr)
    if (sexItemByCode) {
        return sexItemByCode.dictionaryName
    }
    // 兼容旧数据：如果是数字，使用默认映射
    if (sexCode === 1 || sexCode === '1') return '男'
    if (sexCode === 0 || sexCode === '0') return '女'
    return ''
}

// 用户信息接收
const tableData = ref([])
// 用户信息请求
const GetUser = () => {
    myaxios({
        url: "api/User/GetUserList",
        method: "get",
        params: {
            Pageindex: pageinfo.Pageindex,
            PageSize: pageinfo.PageSize,
            UserAccount: pageinfo.UserAccount,
            UserName: pageinfo.UserName,
            PositionId: pageinfo.PositionId,
            Status: pageinfo.Status,
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                tableData.value = res.data.data?.data || [];
                pageinfo.listCount = res.data.data?.listCount || 0;
                pageinfo.pageCount = res.data.data?.pageCount || 0;
            } else {
                ElMessage.error(res.data.message || '获取用户列表失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('获取用户列表失败');
        })
}
// 重置
const resetUser = () => {
    pageinfo.UserAccount = "";
    pageinfo.UserName = "";
    pageinfo.PositionId = null;
    pageinfo.Status = null;
    pageinfo.Pageindex = 1;
}
// 新增
const handleAdd = () => {
    dialogTitle.value = '新增'
    isEdit.value = false
    resetUserForm()
    dialogVisible.value = true
    // 确保下拉数据已加载，每次打开对话框时都刷新性别选项以确保同步
    if (PositionTableData.value.length === 0) GetPosition()
    if (OrganizationTreeData.value.length === 0) GetOrganizationTree()
    if (RoleTableData.value.length === 0) GetRole()
    // 每次都重新加载性别选项，确保与字典管理同步
    GetSexOptions()
}
// 重置表单
const resetUserForm = () => {
    userForm.userId = null
    userForm.userAccount = ''
    userForm.userName = ''
    userForm.userSex = null
    userForm.userPhone = ''
    userForm.positionId = null
    userForm.organizationId = null
    userForm.roleIds = []
    userForm.userSort = 0
    userForm.userState = 1
    userForm.userNote = ''
    // 清除表单验证
    userFormRef.value?.clearValidate()
}
// 对话框关闭
const handleDialogClose = () => {
    resetUserForm()
}
// 保存用户
const handleSave = () => {
    console.log('原始表单数据:', userForm)
    userFormRef.value?.validate((valid) => {
        if (valid) {
            const url = isEdit.value ? 'api/User/UpdateUser' : 'api/User/AddUser'
            const method = isEdit.value ? 'put' : 'post'
            // 性别使用字典表的 dictionaryId，其他字段是后端DTO的字段
            // 处理 userSex：使用字典的 dictionaryId，确保是 Int32 范围内的数字
            // Int32 范围：-2,147,483,648 到 2,147,483,647
            let userSexValue: number = 0 // 默认值
            if (userForm.userSex !== null && userForm.userSex !== undefined) {
                const sexNum = Number(userForm.userSex)
                if (!isNaN(sexNum) && isFinite(sexNum)) {
                    const INT32_MAX = 2147483647
                    const INT32_MIN = -2147483648

                    // 如果 dictionaryId 在 Int32 范围内，直接使用
                    if (sexNum >= INT32_MIN && sexNum <= INT32_MAX) {
                        userSexValue = Math.floor(sexNum)
                    } else {
                        // 如果 dictionaryId 超出范围，根据字典名称映射到标准值（男=1，女=0）
                        const sexOption = SexOptions.value.find(item => item.dictionaryId === sexNum)
                        if (sexOption) {
                            const name = sexOption.dictionaryName || ''
                            if (name.includes('男') || name.includes('Male') || name.includes('M')) {
                                userSexValue = 1
                            } else if (name.includes('女') || name.includes('Female') || name.includes('F')) {
                                userSexValue = 0
                            } else {
                                userSexValue = 0 // 默认值
                            }
                            console.warn('性别 dictionaryId 超出 Int32 范围，根据字典名称映射:', userSexValue, '字典名称:', name, 'dictionaryId:', sexNum)
                        } else {
                            console.warn('性别值超出 Int32 范围，且未找到对应的字典选项，使用默认值 0:', sexNum)
                            userSexValue = 0
                        }
                    }
                }
            }

            // 根据 Swagger 文档，后端期望的是 camelCase 格式的扁平对象
            // 性别使用字典表的 dictionaryId，其他字段是后端DTO的字段
            // 必填字段：userAccount, userName, userPhone, userNote - 确保不是空字符串
            const userAccount = userForm.userAccount ? String(userForm.userAccount).trim() : ''
            const userName = userForm.userName ? String(userForm.userName).trim() : ''
            const userPhone = userForm.userPhone ? String(userForm.userPhone).trim() : ''
            const userNote = userForm.userNote ? String(userForm.userNote).trim() : ''

            // 验证必填字段
            if (!userAccount || userAccount.length === 0) {
                ElMessage.warning('请输入用户账号')
                return
            }
            if (!userName || userName.length === 0) {
                ElMessage.warning('请输入用户姓名')
                return
            }
            if (!userPhone || userPhone.length === 0) {
                ElMessage.warning('请输入手机号')
                return
            }
            if (!userNote || userNote.length === 0) {
                ElMessage.warning('请输入备注')
                return
            }

            // 根据 Swagger 文档，字段名使用 camelCase 格式，直接发送扁平对象
            // 性别使用字典表的 dictionaryId，其他字段是后端DTO的字段
            // 当 dictionaryId 超出 Int32 范围时，尝试从 dictionaryCode 中提取数字，或使用默认值
            const submitData: any = {
                userId: userForm.userId !== null ? Number(userForm.userId) : 0,
                userAccount: userAccount,
                userName: userName,
                userPassword: '', // 新增时可以为空
                userSex: userSexValue, // 已经是数字，默认值为 0
                userPhone: userPhone,
                positionId: userForm.positionId !== null ? Number(userForm.positionId) : 0,
                organizationId: userForm.organizationId !== null ? Number(userForm.organizationId) : 0,
                roleIds: Array.isArray(userForm.roleIds)
                    ? userForm.roleIds.map(id => Number(id)).filter(id => !isNaN(id))
                    : [],
                userSort: Number(userForm.userSort) || 0,
                userState: Number(userForm.userState) || 1,
                userNote: userNote
            }

            // 如果是编辑模式且有 userId，确保 userId 是数字
            if (isEdit.value && userForm.userId) {
                submitData.userId = Number(userForm.userId)
            }

            console.log('提交数据:', submitData)
            console.log('userSex 类型:', typeof submitData.userSex, '值:', submitData.userSex)
            console.log('userSex 是否在 Int32 范围:',
                submitData.userSex === null || (submitData.userSex >= -2147483648 && submitData.userSex <= 2147483647))
            console.log('必填字段检查:', {
                userAccount: submitData.userAccount,
                userName: submitData.userName,
                userPhone: submitData.userPhone,
                userNote: submitData.userNote
            })
            myaxios({
                url: url,
                method: method,
                data: submitData
            })
                .then(res => {
                    if (res.data.code === 200) {
                        ElMessage.success(res.data.message || '保存成功')
                        dialogVisible.value = false
                        GetUser() // 刷新列表
                    } else {
                        ElMessage.error(res.data.message || '保存失败')
                    }
                })
                .catch(err => {
                    console.log('保存用户错误:', err)
                    console.log('错误响应:', err.response)
                    if (err.response && err.response.data) {
                        if (err.response.data.errors) {
                            // 处理验证错误
                            const errors = err.response.data.errors
                            const errorMessages = []
                            for (const field in errors) {
                                errorMessages.push(...errors[field])
                            }
                            ElMessage.error(errorMessages.join('; '))
                        } else {
                            ElMessage.error(err.response.data.message || '保存失败')
                        }
                    } else {
                        ElMessage.error('保存失败')
                    }
                })
        } else {
            ElMessage.warning('请填写必填项')
        }
    })
}
// 编辑
const handleEdit = async (row: any) => {
    dialogTitle.value = '编辑'
    isEdit.value = true
    resetUserForm()
    dialogVisible.value = true

    // 确保下拉数据已加载，每次打开对话框时都刷新性别选项以确保同步
    if (PositionTableData.value.length === 0) GetPosition()
    if (OrganizationTreeData.value.length === 0) GetOrganizationTree()
    if (RoleTableData.value.length === 0) GetRole()
    // 每次都重新加载性别选项，确保与字典管理同步，并等待加载完成
    await GetSexOptions()

    // 等待 DOM 更新，确保 SexOptions 已经渲染到下拉框中
    await nextTick()

    // 获取用户详情并反填
    // 如果 row 中已经有完整数据，直接使用
    userForm.userId = row.userId || null
    userForm.userAccount = row.userAccount || ''
    userForm.userName = row.userName || ''

    // 处理性别：匹配 SexOptions 中的选项
    if (row.userSex !== undefined && row.userSex !== null && row.userSex !== '') {
        const sexNum = Number(row.userSex)
        if (!isNaN(sexNum) && SexOptions.value.length > 0) {
            // 方法1：通过 dictionaryId 匹配
            let sexOption = SexOptions.value.find(item => {
                const itemId = Number(item.dictionaryId)
                return itemId === sexNum || item.dictionaryId === sexNum
            })

            // 方法2：如果没找到，通过 dictionaryCode 匹配（row.userSex 可能是标准值 0/1）
            if (!sexOption) {
                sexOption = SexOptions.value.find(item => {
                    const codeNum = Number(item.dictionaryCode)
                    return codeNum === sexNum || item.dictionaryCode === String(sexNum)
                })
            }

            // 方法3：如果还是没找到，根据标准值映射（0=女，1=男）
            if (!sexOption) {
                if (sexNum === 0 || sexNum === 1) {
                    // 查找名称包含"女"或"男"的选项
                    if (sexNum === 0) {
                        sexOption = SexOptions.value.find(item =>
                            item.dictionaryName?.includes('女') ||
                            item.dictionaryName?.includes('Female') ||
                            item.dictionaryCode === '0'
                        )
                    } else if (sexNum === 1) {
                        sexOption = SexOptions.value.find(item =>
                            item.dictionaryName?.includes('男') ||
                            item.dictionaryName?.includes('Male') ||
                            item.dictionaryCode === '1'
                        )
                    }
                }
            }

            if (sexOption) {
                // 找到匹配项，使用其 dictionaryId
                userForm.userSex = Number(sexOption.dictionaryId)
            } else {
                // 如果都找不到，使用原始值（让 el-select 尝试匹配）
                userForm.userSex = sexNum
            }
        } else {
            userForm.userSex = null
        }
    } else {
        userForm.userSex = null
    }

    // 等待 DOM 更新，确保 el-select 能正确显示
    await nextTick()
    userForm.userPhone = row.userPhone || ''
    userForm.positionId = row.positionId || null
    userForm.organizationId = row.organizationId || null
    // 处理角色：可能是单个 roleId 或 roleIds 数组
    if (row.roleIds && Array.isArray(row.roleIds)) {
        userForm.roleIds = row.roleIds
    } else if (row.roleId) {
        userForm.roleIds = [row.roleId]
    } else {
        userForm.roleIds = []
    }
    userForm.userSort = row.userSort || 0
    userForm.userState = row.userState !== undefined ? row.userState : 1
    userForm.userNote = row.userNote || ''
}
// 删除单个用户
const handleDelete = (row: any) => {
    ElMessageBox.confirm(
        '确认删除这条信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            myaxios({
                url: "/api/User/DeleteUser",
                method: "delete",
                params: { userId: row.userId }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        GetUser();
                        ElMessage.success(res.data.message || '删除成功');
                    } else {
                        ElMessage.error(res.data.message || '删除失败');
                    }
                })
                .catch(err => {
                    console.log(err);
                    ElMessage.error('删除失败');
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}
// 批量删除
const handleBatchDelete = () => {
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要删除的用户');
        return;
    }
    ElMessageBox.confirm(
        '确认删除这些信息吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            const userIds = multipleSelection.value.map((x: any) => x.userId).toString();
            myaxios({
                url: "/api/User/BatchDeleteUser",
                method: "delete",
                params: {
                    userIds: userIds
                }
            })
                .then(res => {
                    if (res.data.code == 200) {
                        GetUser();
                        ElMessage.success(res.data.message);
                    } else {
                        ElMessage.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                    ElMessage.error('删除失败');
                })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '已取消',
            })
        })
}

// 批量启用
const handleBatchEnable = () => {
    const userIds = multipleSelection.value.map((x: any) => x.userId).toString();
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要启用的用户');
        return;
    }
    myaxios({
        url: "/api/User/BatchEnableUser",
        method: "put",
        params: {
            userIds: userIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                GetUser();
                ElMessage.success(res.data.message || '启用成功');
            } else {
                ElMessage.error(res.data.message || '启用失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('启用失败');
        })
}

// 批量停用
const handleBatchDisable = () => {
    const userIds = multipleSelection.value.map((x: any) => x.userId).toString();
    if (multipleSelection.value.length === 0) {
        ElMessage.warning('请选择要停用的用户');
        return;
    }
    myaxios({
        url: "/api/User/BatchDisableUser",
        method: "put",
        params: {
            userIds: userIds
        }
    })
        .then(res => {
            if (res.data.code === 200) {
                GetUser();
                ElMessage.success(res.data.message || '停用成功');
            } else {
                ElMessage.error(res.data.message || '停用失败');
            }
        })
        .catch(err => {
            console.log(err);
            ElMessage.error('停用失败');
        })
}

// 钩子函数
onMounted(() => {
    GetUser(); // 用户信息请求
    GetPosition(); // 岗位信息请求
    GetOrganizationTree(); // 部门树形数据请求
    GetRole(); // 角色信息请求
    GetSexOptions(); // 性别字典选项请求
})

// 侦听器
watch(pageinfo, () => {
    GetUser(); // 用户信息请求
}, { deep: true })

</script>

<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}

:deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

:deep(.el-checkbox) {
    margin-right: 0;
    margin-bottom: 5px;
}
</style>
